#include "tcpuserconnect.h"
#include "protocol.h"
#include "dbcontroler.h"
#include <QMessageBox>
#include <QMap>
#include "mytcpserver.h"

#include <QDateTime>
#include "WorkServe/userservice.h"
#include "deallogicobj.h"
TcpUserConnect::TcpUserConnect()
{
    connect(this,&TcpUserConnect::readyRead,
            this,&TcpUserConnect::RecvMsg);

    connect(this,&TcpUserConnect::disconnected,
            this,&TcpUserConnect::ActForDisconnect);

}

void TcpUserConnect::setUserName(QString Un)
{
    _UserName=Un;
}

QString TcpUserConnect::getUserName()
{
    return _UserName;
}

void TcpUserConnect::_doDownLoad(PDU *recvPDU)
{
    QString UserName=recvPDU->caData;
    ////破坏了单一职责原则
    DBControler::get_instance()
            ->_DownloadUpdate(UserName.toUtf8()
                              .toStdString().c_str());

    emit ThrowDownload(this,UserName);
}

void TcpUserConnect::RecvMsg()//接收信息
{
    //qDebug()<<__FILE__<<__LINE__<<this->bytesAvailable();
    uint PDULength=0;
    this->read((char*)&PDULength,sizeof(uint));
    uint Msglength=PDULength-sizeof(PDU);
    PDU *recvPDU=get_PDU(Msglength);
    this->read((char*)recvPDU+sizeof(uint),PDULength-sizeof(uint));


    DealLogicObj::getInstance().DoHandler(recvPDU->MessageType,
                                          std::shared_ptr<PDU>(recvPDU,std::free),this);
    recvPDU=nullptr;
}


void TcpUserConnect::SendToClient(PDU *RespondData)
{
    if(RespondData==nullptr)return;
    write((char*)RespondData,RespondData->PDULength);
    free(RespondData);
    RespondData=nullptr;
}

void TcpUserConnect::ActForDisconnect()
{
    QString UserName=getUserName();
    DBControler::get_instance()
            ->_DownloadUpdate(UserName.toUtf8().toStdString().c_str());

    emit ThrowDownload(this,UserName);
}

void TcpUserConnect::SendMsg(myuint Type, QJsonObject Info)
{
    QJsonDocument dc(Info);
    QString Body=dc.toJson();
    std::shared_ptr<PDU>MSG=std::shared_ptr<PDU>(get_PDU(Body.toUtf8().toStdString().length()));
    MSG->MessageType=Type;
    memcpy((char*)MSG.get()+sizeof (PDU),
           Body.toUtf8().toStdString().c_str(),
           Body.toUtf8().toStdString().length());
    write((char*)MSG.get(),MSG->PDULength);
}
